﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace desktopEnglish.utils
{
    class UtilSerialize
    {
        public static void SerializeToFile(Object o, string filePath)
        {
            FileStream fs = null;
            if (!File.Exists(filePath))
            {
                int index = filePath.LastIndexOf("\\");
                //创建一级目录
                Directory.CreateDirectory(filePath.Substring(0,index));
                fs = File.Create(filePath); 
            }
            if(fs == null)
            {
                fs = new FileStream(filePath, FileMode.OpenOrCreate);
            }
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, o);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "      序列化");
            }
            finally
            {
                fs.Flush();
                fs.Close();
            }
        }
        public static Object DeserializeFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return null;
            }
            FileStream fs = new FileStream(filePath, FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                return formatter.Deserialize(fs);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "反序列化");
                return null;
            }
            finally
            {
                fs.Flush();
                fs.Close();
            }
        }
    }
}
